package videohelper

import (
	"bytes"
	"log"
	"os/exec"
	"strconv"
	"strings"
)

/**
 * @param src 源视频
 * @param dst 需要生成的地址
 * @param watermark 水印图片地址
 * @param position 水印位置 lt-左上角 rt-右上角 lb-左下角 rb-右下角
 * ffmpeg -i e1829e3ae7b64f75a3321f1bcc66928b_h264.mp4 -i logo4-small.png -filter_complex "[1:v]scale=150:40[watermark];[0:v][watermark]overlay=main_w-overlay_w-10:main_h-overlay_h-10" -c:a copy e1829e3ae7b64f75a3321f1bcc66928b_logo.mp4
 */
func VideoWaterMark(src, dst, watermark, position string) (isSucc bool, err error) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("VideoWaterMark panic err, ", r)
		}
	}()
	pos := "10:10"
	if position == "rt" {
		pos = "main_w-overlay_w-10:10"
	} else if position == "lb" {
		pos = "10:main_h-overlay_h-10"
	} else if position == "rb" {
		pos = "main_w-overlay_w-10:main_h-overlay_h-10"
	}
	cmd := exec.Command(
		"ffmpeg",
		"-i",
		src,
		"-i",
		watermark,
		"-filter_complex",
		"[1:v]scale=150:40[watermark];[0:v][watermark]overlay="+pos,
		"-c:a",
		"copy",
		dst)

	var out bytes.Buffer
	cmd.Stdout = &out
	err = cmd.Run()
	if err != nil {
		log.Println("VideoWaterMark ffmpeg exec err, ", err)
		return
	}
	isSucc = true
	return
}

// 获取视频快照
// ffmpeg -i input_video.mp4 -ss 00:00:05 -frames:v 1 -f image2 output_snapshot.png
func VideoSnapshot(videoSrc, poster string) (isSucc bool, err error) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("VideoSnapshot panic err, ", r)
		}
	}()
	cmd := exec.Command(
		"ffmpeg",
		"-i",
		videoSrc,
		"-ss",
		"00:00:01",
		"-frames:v",
		"1",
		"-f",
		"image2",
		poster,
	)
	var out bytes.Buffer
	cmd.Stdout = &out
	err = cmd.Run()
	if err != nil {
		log.Println("VideoSnapshot ffmpeg exec err, ", err)
		return
	}
	isSucc = true
	return
}

// 获取视频宽高
// ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 input.mp4
func VideoSize(fp string) (width, height int, err error) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("VideoSize panic err, ", r)
		}
	}()
	cmd := exec.Command(
		"ffprobe",
		"-v",
		"error",
		"-select_streams",
		"v:0",
		"-show_entries",
		"stream=width,height",
		"-of",
		"csv=p=0",
		fp,
	)

	var out bytes.Buffer
	cmd.Stdout = &out
	err = cmd.Run()
	if err != nil {
		log.Println("VideoSize ffmpeg exec err, ", err)
		return
	}
	result := out.String()
	result = strings.Replace(result, "\r\n", "", -1)
	result = strings.Replace(result, "\n", "", -1)
	result = strings.Replace(result, "\r", "", -1)
	strs := strings.Split(result, ",")
	if len(strs) == 2 {
		width, err = strconv.Atoi(strs[0])
		if err != nil {
			return
		}
		height, err = strconv.Atoi(strs[1])
	}
	return
}
